package com.blockchain.console.service.content.achieve;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;

import com.blockchain.common.enums.AdvertisementStatus;
import com.blockchain.common.enums.SbType;
import com.blockchain.console.config.ConsoleConst;
import com.blockchain.console.service.content.AdvertisementManage;
import com.blockchain.console.service.content.entity.Advertisement;
import com.blockchain.console.service.content.entity.AdvertisementRecord;
import com.blockchain.console.service.content.query.AdvertisementRecordQuery;
import com.blockchain.framework.http.upload.FileStore;
import com.blockchain.framework.http.upload.UploadFile;
import com.blockchain.framework.service.ServiceFactory;
import com.blockchain.framework.service.ServiceResource;
import com.blockchain.framework.service.exception.ParameterException;
import com.blockchain.framework.service.query.ArrayParser;
import com.blockchain.framework.service.query.ItemParser;
import com.blockchain.framework.service.query.Paging;
import com.blockchain.framework.service.query.PagingResult;
import com.blockchain.util.StringHelper;
import com.blockchain.util.parser.EnumParser;
import com.blockchain.variables.FileType;

public class AdvertisementManageImpl extends AbstractInformationService
		implements AdvertisementManage {

	public static class AdvertisementManageFactory implements
			ServiceFactory<AdvertisementManage> {

		@Override
		public AdvertisementManage newInstance(ServiceResource serviceResource) {
			return new AdvertisementManageImpl(serviceResource);
		}

	}

	protected static final ArrayParser<AdvertisementRecord> ARRAY_PARSER = new ArrayParser<AdvertisementRecord>() {

		@Override
		public AdvertisementRecord[] parse(ResultSet resultSet)
				throws SQLException {
			ArrayList<AdvertisementRecord> list = null;
			while (resultSet.next()) {
				AdvertisementRecord record = new AdvertisementRecord();
				record.id = resultSet.getInt(1);
				record.sortIndex = resultSet.getInt(2);
				record.title = resultSet.getString(3);
				record.url = resultSet.getString(4);
				record.imageCode = resultSet.getString(5);
				record.publisherId = resultSet.getInt(6);
				record.showTime = resultSet.getTimestamp(7);
				record.unshowTime = resultSet.getTimestamp(8);
				record.createTime = resultSet.getTimestamp(9);
				record.updateTime = resultSet.getTimestamp(10);
				record.publisherName = resultSet.getString(11);
				Timestamp currentTime = resultSet.getTimestamp(12);
				if (currentTime.getTime() < record.showTime.getTime()) {
					record.status = AdvertisementStatus.DSJ;
				} else if (currentTime.getTime() < record.unshowTime.getTime()) {
					record.status = AdvertisementStatus.YSJ;
				} else {
					record.status = AdvertisementStatus.YXJ;
				}
				record.sblx = EnumParser.parse(SbType.class, resultSet.getString(13));
				if (list == null) {
					list = new ArrayList<>();
				}
				list.add(record);
			}
			return list == null || list.size() == 0 ? null : list
					.toArray(new AdvertisementRecord[list.size()]);
		}
	};
	protected static final ItemParser<AdvertisementRecord> ITEM_PARSER = new ItemParser<AdvertisementRecord>() {

		@Override
		public AdvertisementRecord parse(ResultSet resultSet)
				throws SQLException {
			AdvertisementRecord record = null;
			if (resultSet.next()) {
				record = new AdvertisementRecord();
				record.id = resultSet.getInt(1);
				record.sortIndex = resultSet.getInt(2);
				record.title = resultSet.getString(3);
				record.url = resultSet.getString(4);
				record.imageCode = resultSet.getString(5);
				record.publisherId = resultSet.getInt(6);
				record.showTime = resultSet.getTimestamp(7);
				record.unshowTime = resultSet.getTimestamp(8);
				record.createTime = resultSet.getTimestamp(9);
				record.updateTime = resultSet.getTimestamp(10);
				record.publisherName = resultSet.getString(11);
				Timestamp currentTime = resultSet.getTimestamp(12);
				if (currentTime.getTime() < record.showTime.getTime()) {
					record.status = AdvertisementStatus.DSJ;
				} else if (currentTime.getTime() < record.unshowTime.getTime()) {
					record.status = AdvertisementStatus.YSJ;
				} else {
					record.status = AdvertisementStatus.YXJ;
				}
				record.sblx = EnumParser.parse(SbType.class, resultSet.getString(13));
			}
			return record;
		}

	};

	protected static final String SELECT_ALL_SQL = "SELECT T5016.F01,T5016.F02,T5016.F03,T5016.F04,T5016.F05,T5016.F06,T5016.F07,T5016.F08,T5016.F09,T5016.F10,T7011.F04 AS F11,CURRENT_TIMESTAMP() AS F12,T5016.F11 AS sblx FROM T5016 INNER JOIN "
			+ ConsoleConst.DB_CONSOLE + ".T7011 ON T5016.F06 = T7011.F01";

	public AdvertisementManageImpl(ServiceResource serviceResource) {
		super(serviceResource);
	}

	
	@Override
	public AdvertisementRecord get(int id) throws Throwable {
		if (id <= 0) {
			return null;
		}
		return select(getConnection(), ITEM_PARSER, SELECT_ALL_SQL
				+ " WHERE T5016.F01 = ?", id);
	}

	@Override
	public int add(Advertisement advertisement) throws Throwable {
		if (advertisement == null) {
			throw new ParameterException("没有给出广告信息");
		}
		String title;
		String url;
		String imageCode;
		Timestamp showTime;
		Timestamp unshowTime;
		{
			title = advertisement.getTitle();
			if (StringHelper.isEmpty(title)) {
				throw new ParameterException("必须指定广告标题");
			}
			if (title.length() > 50) {
				throw new ParameterException("广告标题必须小于50个字符");
			}
			showTime = advertisement.getShowTime();
			if (showTime == null) {
				throw new ParameterException("必须指定上架时间");
			}
			unshowTime = advertisement.getUnshowTime();
			if (unshowTime == null) {
				throw new ParameterException("必须指定下架时间");
			}
			UploadFile image = advertisement.getImage();
			if (image == null) {
				throw new ParameterException("必须上传广告图片");
			}

			FileStore fileStore = serviceResource.getResource(FileStore.class);
			imageCode = fileStore.upload(
					FileType.ADVERTISEMENT_IMAGE.ordinal(), image)[0];
			url = advertisement.getURL();
		}

		return insert(
				getConnection(),
				"INSERT INTO T5016 SET F02 = ?,F03 = ?,F04 = ?,F05 = ?,F06 = ?,F07 = ?,F08 = ?,F09 = CURRENT_TIMESTAMP(),F11=?",
				advertisement.getSortIndex(), title, url, imageCode,
				serviceResource.getSession().getAccountId(), showTime,
				unshowTime,advertisement.getSblx());
	}

	@Override
	public void update(int id, Advertisement advertisement) throws Throwable {
		if (id <= 0) {
			throw new ParameterException("没有给出广告ID");
		}
		if (advertisement == null) {
			throw new ParameterException("没有给出广告信息");
		}
		String title;
		String url;

		Timestamp showTime;
		Timestamp unshowTime;
		{
			title = advertisement.getTitle();
			if (StringHelper.isEmpty(title)) {
				throw new ParameterException("必须指定广告标题");
			}
			if (title.length() > 50) {
				throw new ParameterException("广告标题必须小于50个字符");
			}
			showTime = advertisement.getShowTime();
			if (showTime == null) {
				throw new ParameterException("必须指定上架时间");
			}
			unshowTime = advertisement.getUnshowTime();
			if (unshowTime == null) {
				throw new ParameterException("必须指定下架时间");
			}
			url = advertisement.getURL();
		}
		UploadFile image = advertisement.getImage();
		if (image == null) {
			execute(getConnection(),
					"UPDATE T5016 SET F02 = ?,F03 = ?,F04 = ?,F07 = ?,F08 = ?,F11=? WHERE F01 = ?",
					advertisement.getSortIndex(), title, url, showTime,
					unshowTime,advertisement.getSblx(), id);
		} else {
			FileStore fileStore = serviceResource.getResource(FileStore.class);
			String imageCode = fileStore.upload(
					FileType.ADVERTISEMENT_IMAGE.ordinal(), image)[0];
			execute(getConnection(),
					"UPDATE T5016 SET F02 = ?,F03 = ?,F04 = ?,F05 = ?,F07 = ?,F08 = ?,F11=? WHERE F01 = ?",
					advertisement.getSortIndex(), title, url, imageCode,
					showTime, unshowTime,advertisement.getSblx(), id);
		}

	}

	@Override
	public void delete(int... ids) throws Throwable {
		if (ids == null || ids.length == 0) {
			return;
		}
		serviceResource.openTransactions();
		try (Connection connection = getConnection();
				PreparedStatement pstmt = connection
						.prepareStatement("DELETE FROM T5016 WHERE F01 = ?");) {
			for (int id : ids) {
				if (id <= 0) {
					continue;
				}
				pstmt.setInt(1, id);
				pstmt.addBatch();
			}
			pstmt.executeBatch();
		}
	}

	@Override
	public PagingResult<AdvertisementRecord> search(
			AdvertisementRecordQuery query, Paging paging) throws Throwable {
		StringBuilder s = new StringBuilder();
		s.append("SELECT T5016.F01,T5016.F02,T5016.F03,T5016.F04,T5016.F05,T5016.F06,T5016.F07,T5016.F08,T5016.F09,T5016.F10,T7011.F04 AS F11,CURRENT_TIMESTAMP() AS F12,T5016.F11 AS sblx FROM T5016 INNER JOIN "
			+ ConsoleConst.DB_CONSOLE + ".T7011 ON T5016.F06 = T7011.F01");
		ArrayList<Object> parameters = new ArrayList<>();
		if (query != null) {
			SbType sblx=query.getSblx();
			if (sblx !=null) {
				s.append(" AND T5016.F11 = ?");
				parameters.add(sblx);
			}
			AdvertisementStatus status=query.getStatus();
			Timestamp currentTime = new Timestamp(System.currentTimeMillis()); 
			if(status!=null){
				if(status==AdvertisementStatus.DSJ){
					s.append(" AND DATE(T5016.F07) > ? ");
					parameters.add(currentTime);
				}
				else if(status==AdvertisementStatus.YSJ){
					s.append(" AND DATE(T5016.F08) >= ? ");
					s.append(" AND DATE(T5016.F07) <= ? ");
					parameters.add(currentTime);
					parameters.add(currentTime);
				}
				else if(status==AdvertisementStatus.YXJ){
					s.append(" AND DATE(T5016.F08) < ? ");
					parameters.add(currentTime);
				}
			}
		  }
		  s.append(" ORDER BY T5016.F02 DESC,T5016.F10 DESC");
		  PagingResult<AdvertisementRecord> pagingResult = selectPaging(
					getConnection(ConsoleConst.DB_INFORMATION), ARRAY_PARSER, paging,
					s.toString(), parameters);
		
		  return pagingResult;
	}

	

}
